package com.mantru.iotpot.Cook;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.mantru.iotpot.ApplicationClass;
import com.mantru.iotpot.Cook.adapter.NunberKeyAdapter;
import com.mantru.iotpot.Cook.adapter.OilPumpAdapter;
import com.mantru.iotpot.DateClass.oil_pump;
import com.mantru.iotpot.DateClass.pump_name_weight;
import com.mantru.iotpot.R;
import com.mantru.iotpot.Util.ToastUtils;
import com.mantru.iotpot.eventbus.RefreshEvent;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class SetOilPumpActivity extends AppCompatActivity implements View.OnClickListener, NunberKeyAdapter.OnNumberClickListener, OilPumpAdapter.OnPumpSelectedListener {

    private int way;//第几个油泵
    private LinearLayout back;
    private Button water,combination1,combination2,combination3;
    private TextView nametext;
    private LinearLayout delete;
    private GridView oil_pump_combination,numberkey;
    private TextView number;
    private Button confirm;
    private ApplicationClass ac;
    private List<oil_pump> pump = new ArrayList<>();//用于存放六种喷泵组合配置
    private TextView name1,name2,name3,text1,text2,text3;
    private LinearLayout background,way1,way2,way3;//水、油、生粉水的父容器
    private OilPumpAdapter oilPumpr; // 声明全局变量
    private int type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_oil_pump);
        ac = (ApplicationClass) getApplication();// 初始化 ApplicationClass
        Intent intent = getIntent();
        way = intent.getIntExtra("oil_pump_num",0);
        type = intent.getIntExtra("type",-1);
        initialization();//初始化控件
        getJson();//解析json数据
        starUI();//初始化界面的数据（默认选择的选项高亮显示，并且加载水、油或者是组合1、2、3）
    }

    //初始化控件
    private void initialization(){
        back = findViewById(R.id.set_oil_pump_back);
        water = findViewById(R.id.set_oil_pump_water);
        combination1 = findViewById(R.id.set_oil_pump_combination1);
        combination2 = findViewById(R.id.set_oil_pump_combination2);
        combination3 = findViewById(R.id.set_oil_pump_combination3);
        nametext = findViewById(R.id.set_oil_pump_name);
        delete = findViewById(R.id.set_oil_pump_del);
        oil_pump_combination = findViewById(R.id.set_oil_pump_gridview2);//组合1、2、3的11个油泵gridview
        numberkey = findViewById(R.id.set_oil_pump_gridview3);//加载数字键的gridview
        number = findViewById(R.id.set_oil_pump_number_text);
        confirm = findViewById(R.id.set_oil_pump_confirm);
        name1 = findViewById(R.id.set_oil_pump_water_name1);
        name2 = findViewById(R.id.set_oil_pump_water_name2);
        name3 = findViewById(R.id.set_oil_pump_water_name3);
        text1 = findViewById(R.id.set_oil_pump_water_text1);
        text2 = findViewById(R.id.set_oil_pump_water_text2);
        text3 = findViewById(R.id.set_oil_pump_water_text3);
        background = findViewById(R.id.set_oil_pump_water_background);
        way1 = findViewById(R.id.set_oil_pump_water_way1);
        way2 = findViewById(R.id.set_oil_pump_water_way2);
        way3 = findViewById(R.id.set_oil_pump_water_way3);
        back.setOnClickListener(this);
        water.setOnClickListener(this);
        combination1.setOnClickListener(this);
        combination2.setOnClickListener(this);
        combination3.setOnClickListener(this);
        delete.setOnClickListener(this);
        confirm.setOnClickListener(this);
        way1.setOnClickListener(this);
        way2.setOnClickListener(this);
        way3.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.set_oil_pump_back){//点击返回按钮
            EventBus.getDefault().postSticky(new RefreshEvent(RefreshEvent.REFRESH_TEXT));
            finish();
        } else if (v.getId() == R.id.set_oil_pump_confirm) {//点击确定，将油泵的数据保存上去
            //先将修改的数据更新到数组中
            // 更新选中项的文本
            if (oilPumpr != null) {
                String newText = number.getText().toString();
                oilPumpr.updateSelectedText(newText);
            }
            oil_pump oil = updataWeight();
            boolean result = ac.SaveSQLData_Handing_Config_Nozzle_Entity(
                    Integer.parseInt(oil.getConfig_id()),
                    Integer.parseInt(oil.getNozzle1_value()),
                    Integer.parseInt(oil.getNozzle2_value()),
                    Integer.parseInt(oil.getNozzle3_value()),
                    Integer.parseInt(oil.getNozzle4_value()),
                    Integer.parseInt(oil.getNozzle5_value()),
                    Integer.parseInt(oil.getNozzle6_value()),
                    Integer.parseInt(oil.getNozzle7_value()),
                    Integer.parseInt(oil.getNozzle8_value()),
                    Integer.parseInt(oil.getNozzle9_value()),
                    Integer.parseInt(oil.getNozzle10_value()),
                    Integer.parseInt(oil.getNozzle11_value()),
                    type
            );//将选中的油泵中的数据保存下来
            if (result){
                //Toast.makeText(this, "保存油泵配置成功！", Toast.LENGTH_SHORT).show();
                ToastUtils.show(this, "保存油泵配置成功！");
            } else {
                //Toast.makeText(this, "保存油泵配置失败，请重试！", Toast.LENGTH_SHORT).show();
                ToastUtils.show(this, "保存油泵配置失败，请重试！");
            }
        } else if (v.getId() == R.id.set_oil_pump_water) {//点击水、油、淀粉水
            way = 1;//默认水（id = 1）高亮
            updataUI();//更新GridView
            setBackground(2);
            setBackground(1);
            water.setBackgroundResource(R.drawable.button13);
            way1.setBackgroundResource(R.drawable.button12);
        } else if (v.getId() == R.id.set_oil_pump_combination1) {//点击组合1
            way = 4;
            updataUI();//更新GridView
            setBackground(2);
            combination1.setBackgroundResource(R.drawable.button13);
            nametext.setText("组合1");
        }else if (v.getId() == R.id.set_oil_pump_combination2) {//点击组合2
            way = 5;
            updataUI();//更新GridView
            setBackground(2);
            combination2.setBackgroundResource(R.drawable.button13);
            nametext.setText("组合2");
        }else if (v.getId() == R.id.set_oil_pump_combination3) {//点击组合3
            way = 6;
            updataUI();//更新GridView
            setBackground(2);
            combination3.setBackgroundResource(R.drawable.button13);
            nametext.setText("组合3");
        } else if (v.getId() == R.id.set_oil_pump_water_way1) {//选择水喷泵
            way = 1;
            setBackground(1);
            way1.setBackgroundResource(R.drawable.button12);
            oil_pump oilPump = pump.get(0);
            number.setText(oilPump.getNozzle9_value());//获取烹饪水的重量
        }else if (v.getId() == R.id.set_oil_pump_water_way2) {//选择油喷泵
            way = 2;
            setBackground(1);
            way2.setBackgroundResource(R.drawable.button12);
            oil_pump oilPump = pump.get(1);
            number.setText(oilPump.getNozzle5_value());//获取植物油的重量
        }else if (v.getId() == R.id.set_oil_pump_water_way3) {//选择生粉水喷泵
            way = 3;
            setBackground(1);
            way3.setBackgroundResource(R.drawable.button12);
            oil_pump oilPump = pump.get(2);
            number.setText(oilPump.getNozzle8_value());//获取生粉水的重量
        } else if (v.getId() == R.id.set_oil_pump_del) {//点击清空之后，将所有喷泵的数据变为0
            if (way >= 1 && way <= 3){
                text1.setText("0");
                text2.setText("0");
                text3.setText("0");
                number.setText("0");
                boolean result = false;
                for (int i = 0;i < 3;i++){
                    result = ac.SaveSQLData_Handing_Config_Nozzle_Entity(i+1,0,0,0,0,0,0,0,0,0,0,0,type);
                }
                if (result){
                    //Toast.makeText(this, "清空成功", Toast.LENGTH_SHORT).show();
                    ToastUtils.show(this, "清空成功");
                }else {
                    //Toast.makeText(this, "清空失败", Toast.LENGTH_SHORT).show();
                    ToastUtils.show(this, "清空失败");
                }
            }else if (way >= 4 && way <= 6){
                deleteAllWeight();//将当前组合的值全部赋值为0
                getOilPumpNameAndWeight(way,2);
                boolean result = ac.SaveSQLData_Handing_Config_Nozzle_Entity(way,0,0,0,0,0,0,0,0,0,0,0,type);
                if (result){
                    //Toast.makeText(this, "清空成功", Toast.LENGTH_SHORT).show();
                    ToastUtils.show(this, "清空成功");
                }else {
                    //Toast.makeText(this, "清空失败", Toast.LENGTH_SHORT).show();
                    ToastUtils.show(this, "清空失败");
                }
            }
        }
    }

    //解析json数据
    private void getJson(){
        for (int i = 0;i < 6;i++){//将所有组合的数据全部保存下来
            String json_data = ac.GetSQLData_Handing_Config_Nozzle_Entity(i+1,type);
            Log.d("SetOilPumpActivity", "json_data: " + json_data);
            try {
                JSONObject jsonObject = new JSONObject(json_data);
                boolean success = jsonObject.getBoolean("success");
                if (success){
                    JSONObject data = jsonObject.getJSONObject("data");
                    String config_id = data.getString("config_id");
                    String nozzle1_value = data.getString("nozzle1_value");
                    String nozzle2_value = data.getString("nozzle2_value");
                    String nozzle3_value = data.getString("nozzle3_value");
                    String nozzle4_value = data.getString("nozzle4_value");
                    String nozzle5_value = data.getString("nozzle5_value");
                    String nozzle6_value = data.getString("nozzle6_value");
                    String nozzle7_value = data.getString("nozzle7_value");
                    String nozzle8_value = data.getString("nozzle8_value");
                    String nozzle9_value = data.getString("nozzle9_value");
                    String nozzle10_value = data.getString("nozzle10_value");
                    String nozzle11_value = data.getString("nozzle11_value");
                    pump.add(new oil_pump(config_id,nozzle1_value,nozzle2_value,nozzle3_value,nozzle4_value,nozzle5_value,
                            nozzle6_value,nozzle7_value,nozzle8_value,nozzle9_value,nozzle10_value,nozzle11_value));
                    // 按照指定格式拼接所有解析到的值
                    String logMessage = "config_id: " + config_id
                            + " nozzle1_value: " + nozzle1_value
                            + " nozzle2_value: " + nozzle2_value
                            + " nozzle3_value: " + nozzle3_value
                            + " nozzle4_value: " + nozzle4_value
                            + " nozzle5_value: " + nozzle5_value
                            + " nozzle6_value: " + nozzle6_value
                            + " nozzle7_value: " + nozzle7_value
                            + " nozzle8_value: " + nozzle8_value
                            + " nozzle9_value: " + nozzle9_value
                            + " nozzle10_value: " + nozzle10_value
                            + " nozzle11_value: " + nozzle11_value;
                    // 打印所有解析到的值
                    Log.d("SetOilPumpActivity", logMessage);
                }
            }catch (Exception e){
                e.printStackTrace();
                Log.d("SetOilPumpActivity", "解析json数据失败");
            }
        }
    }

    //更新GridView
    private void updataUI(){
        if (way >= 1 && way<=3){//显示油、水油泵的布局
            background.setVisibility(View.VISIBLE);
            oil_pump_combination.setVisibility(View.GONE);
            setWay();//更新喷泵的内容
        } else if (way >= 4 && way <= 6) {//显示组合1、2、3的gridview
            background.setVisibility(View.GONE);
            oil_pump_combination.setVisibility(View.VISIBLE);
            //下面更新显示组合1、2、3的gridview（将pump传过去）
            getOilPumpNameAndWeight(way,1);
        }else {
            //Toast.makeText(this, "发生了错误", Toast.LENGTH_SHORT).show();
            ToastUtils.show(this, "发生了错误");
        }
    }

    //将组合的内容更新到水、油、生粉水喷泵中
    private void setWay(){
        nametext.setText("水/油/生粉水");
        for (oil_pump oilPump : pump){
            switch (oilPump.getConfig_id()){
                case "1"://烹饪水，对应nozzle10_value
                    text1.setText(oilPump.getNozzle9_value());
                    if (way == 1){
                        number.setText(oilPump.getNozzle9_value());
                    }
                    break;
                case "2"://植物油，对应nozzle6_value
                    text2.setText(oilPump.getNozzle5_value());
                    if (way == 2){
                        number.setText(oilPump.getNozzle5_value());
                    }
                    break;
                case "3"://淀粉水，对应nozzle9_value
                    text3.setText(oilPump.getNozzle8_value());
                    if (way == 3){
                        number.setText(oilPump.getNozzle8_value());
                    }
                    break;
            }
        }
    }

    //设置喷泵的背景样式
    private void setBackground(int type){
        switch (type){
            case 1:
                way1.setBackgroundResource(R.drawable.touch1);
                way2.setBackgroundResource(R.drawable.touch1);
                way3.setBackgroundResource(R.drawable.touch1);
                break;
            case 2:
                water.setBackgroundResource(R.drawable.touch2);
                combination1.setBackgroundResource(R.drawable.touch2);
                combination2.setBackgroundResource(R.drawable.touch2);
                combination3.setBackgroundResource(R.drawable.touch2);
        }
    }

    //进入页面时初始化ui信息
    private void starUI(){
        if (way == 1){
            water.setBackgroundResource(R.drawable.button13);
            way1.setBackgroundResource(R.drawable.button12);
            setWay();//将组合的内容更新到水、油、生粉水喷泵中
        } else if (way == 2) {
            water.setBackgroundResource(R.drawable.button13);
            way2.setBackgroundResource(R.drawable.button12);
            setWay();//将组合的内容更新到水、油、生粉水喷泵中
        } else if (way == 3) {
            water.setBackgroundResource(R.drawable.button13);
            way3.setBackgroundResource(R.drawable.button12);
            setWay();//将组合的内容更新到水、油、生粉水喷泵中
        } else if (way == 4) {//组合1
            background.setVisibility(View.GONE);
            oil_pump_combination.setVisibility(View.VISIBLE);
            combination1.setBackgroundResource(R.drawable.button13);
            //加载gridview
            getOilPumpNameAndWeight(way,1);
        } else if (way == 5) {
            background.setVisibility(View.GONE);
            oil_pump_combination.setVisibility(View.VISIBLE);
            combination2.setBackgroundResource(R.drawable.button13);
            //加载gridview
            getOilPumpNameAndWeight(way,1);
        } else if (way == 6) {
            background.setVisibility(View.GONE);
            oil_pump_combination.setVisibility(View.VISIBLE);
            combination3.setBackgroundResource(R.drawable.button13);
            //加载gridview
            getOilPumpNameAndWeight(way,1);
        }
        List<String> items = new ArrayList<>();
        for (int i = 1; i <= 9; i++) {
            items.add(String.valueOf(i));
        }
        items.add(""); // 小数点
//        items.add("0");
//        items.add("删除"); // 删除键
        NunberKeyAdapter adapter = new NunberKeyAdapter(this,items,this);
        numberkey.setAdapter(adapter);
    }

    //将获取喷泵信息并且创建喷泵适配器
    private void getOilPumpNameAndWeight(int id,int type){
        oil_pump oilPump = pump.get(id-1);
        List<pump_name_weight> list = new ArrayList<>();
        if (type == 1){//type为1时正常显示喷泵中的内容
            list.add(new pump_name_weight("生抽", oilPump.getNozzle1_value()));
            list.add(new pump_name_weight("老抽", oilPump.getNozzle2_value()));
            list.add(new pump_name_weight("蚝油", oilPump.getNozzle3_value()));
            list.add(new pump_name_weight("动物油", oilPump.getNozzle4_value()));
            list.add(new pump_name_weight("油", oilPump.getNozzle5_value()));
            list.add(new pump_name_weight("盐水", oilPump.getNozzle6_value()));
            list.add(new pump_name_weight("醋", oilPump.getNozzle7_value()));
            list.add(new pump_name_weight("生粉水", oilPump.getNozzle8_value()));
            list.add(new pump_name_weight("烹饪水", oilPump.getNozzle9_value()));
            number.setText(oilPump.getNozzle1_value());
        } else if (type == 2) {//type为2时则是点击清空之后，将喷泵的内容全部变为0
            list.add(new pump_name_weight("生抽", "0"));
            list.add(new pump_name_weight("老抽", "0"));
            list.add(new pump_name_weight("蚝油", "0"));
            list.add(new pump_name_weight("动物油", "0"));
            list.add(new pump_name_weight("油", "0"));
            list.add(new pump_name_weight("盐水", "0"));
            list.add(new pump_name_weight("醋", "0"));
            list.add(new pump_name_weight("生粉水", "0"));
            list.add(new pump_name_weight("水", "0"));
            number.setText("0");
        }
        OilPumpAdapter adapter = new OilPumpAdapter(this, list);
        adapter.setOnPumpSelectedListener(this); // 设置接口
        oil_pump_combination.setAdapter(adapter);
        oil_pump_combination.setNumColumns(3); // 设置为3列
        oilPumpr = adapter; // 保存适配器实例
    }
    @Override
    public void onNumberClick(String num) {
        String currentValue = number.getText().toString();
        Log.d("number", "currentValue: " + currentValue);

        if (num.equals("删除")) {
//            if (currentValue.length() > 0) {
//                String newValue = currentValue.substring(0, currentValue.length() - 1);
//                if (newValue.isEmpty()) {
//                    number.setText("0"); // 如果删除后为空，设置为 "0"
//                } else {
//                    number.setText(newValue);
//                }
//            }
            number.setText("0");
        } else {
            // 如果当前值是 "0"，并且输入的是非零数字，则替换 "0"
            if (currentValue.equals("0")) {
                if (!num.equals("0")) {
                    number.setText(num);
                }
            } else {
                number.setText(currentValue + num);
            }
        }
    }

    //一个用于更新列表中喷泵配置数据的方法
    private oil_pump updataWeight(){
        oil_pump oilPump = pump.get(way-1);
        if (way == 1){
            oilPump.setNozzle9_value(number.getText().toString());//烹饪水，对应nozzle10_value
            text1.setText(number.getText().toString());
        } else if (way == 2) {
            oilPump.setNozzle5_value(number.getText().toString());//植物油，对应nozzle6_value
            text2.setText(number.getText().toString());
        }else if (way == 3) {
            oilPump.setNozzle8_value(number.getText().toString());//淀粉水，对应nozzle9_value
            text3.setText(number.getText().toString());
        }else if (way >= 4 && way <= 6) {
            int n = oilPumpr.getSelectedPosition();
            switch (n){
                case 0:
                    oilPump.setNozzle1_value(number.getText().toString());
                    break;
                case 1:
                    oilPump.setNozzle2_value(number.getText().toString());
                    break;
                case 2:
                    oilPump.setNozzle3_value(number.getText().toString());
                    break;
                case 3:
                    oilPump.setNozzle4_value(number.getText().toString());
                    break;
                case 4:
                    oilPump.setNozzle5_value(number.getText().toString());
                    break;
                case 5:
                    oilPump.setNozzle6_value(number.getText().toString());
                    break;
                case 6:
                    oilPump.setNozzle7_value(number.getText().toString());
                    break;
                case 7:
                    oilPump.setNozzle8_value(number.getText().toString());
                    break;
                case 8:
                    oilPump.setNozzle9_value(number.getText().toString());
                    break;
                case 9:
                    oilPump.setNozzle10_value(number.getText().toString());
                    break;
                case 10:
                    oilPump.setNozzle11_value(number.getText().toString());
                    break;
            }
        }
        return oilPump;
    }

    //将组合1、2、3的喷泵内容变为0并且存储到列表中
    private void deleteAllWeight(){
        Log.d("deleteAllWeight","way: " + way);
        pump.get(way-1).setNozzle1_value("0");
        pump.get(way-1).setNozzle2_value("0");
        pump.get(way-1).setNozzle3_value("0");
        pump.get(way-1).setNozzle4_value("0");
        pump.get(way-1).setNozzle5_value("0");
        pump.get(way-1).setNozzle6_value("0");
        pump.get(way-1).setNozzle7_value("0");
        pump.get(way-1).setNozzle8_value("0");
        pump.get(way-1).setNozzle9_value("0");
        pump.get(way-1).setNozzle10_value("0");
        pump.get(way-1).setNozzle11_value("0");
    }

    @Override
    public void onPumpSelected(String weight) {
        number.setText(weight); // 更新number文本的值
    }
}